package models

import (
	"encoding/json"
	"errors"
	"time"
)

type Post struct {
	PostID      uint64    `gorm:"column:post_id" json:"post_id"`
	Title       string    `gorm:"column:title" binding:"required" json:"title"`
	Content     string    `gorm:"column:content" binding:"required" json:"content"`
	AuthorId    uint64    `gorm:"column:author_id" json:"author_id"`
	CommunityID int64     `gorm:"column:community_id" json:"community_id"`
	Status      int32     `gorm:"column:status" json:"status"`
	CreateTime  time.Time `gorm:"column:create_time" json:"create_time"`
}

func (p *Post) Unmarshalgorm(data []byte) (err error) {
	required := struct {
		Title       string `gorm:"title" db:"title"`
		Content     string `gorm:"content" db:"content"`
		CommunityID int64  `gorm:"community_id" db:"community_id"`
	}{}
	err = json.Unmarshal(data, &required)
	if err != nil {
		return
	} else if len(required.Title) == 0 {
		err = errors.New("帖子标题不能为空")
	} else if len(required.Content) == 0 {
		err = errors.New("帖子内容不能为空")
	} else if required.CommunityID == 0 {
		err = errors.New("未指定版块")
	} else {
		p.Title = required.Title
		p.Content = required.Content
		p.CommunityID = required.CommunityID
	}
	return
}

type ApiPostDetail struct {
	*Post
	VoteNum       int64  `json:"vote_num"`
	AuthorName    string `json:"author_name"`
	CommunityName string `json:"community_name"`
}

func (Post) TableName() string {
	return "post"
}
